package com.hys.app.service.open.order;

import com.hys.app.converter.open.OpenOrderConverter;
import com.hys.app.framework.util.CurrencyUtil;
import com.hys.app.framework.util.DateUtil;
import com.hys.app.model.erp.dto.OrderDTO;
import com.hys.app.model.erp.dto.OrderItemDTO;
import com.hys.app.model.erp.dto.OrderPaymentDTO;
import com.hys.app.model.erp.enums.OrderPaymentStatusEnum;
import com.hys.app.model.erp.enums.OrderSourceEnum;
import com.hys.app.model.erp.enums.OrderTypeEnum;
import com.hys.app.model.open.order.dto.CreateOrderDTO;
import com.hys.app.oauth2.LoginClientHolder;
import com.hys.app.service.erp.OrderManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;

/**
 * 订单对外接口业务层实现
 *
 * @author 张崧
 * @since 2024-04-08
 */
@Service
@Slf4j
public class OrderOpenManagerImpl implements OrderOpenManager {

    @Autowired
    private OpenOrderConverter openOrderConverter;

    @Autowired
    private OrderManager orderManager;

    @Override
    public String create(CreateOrderDTO createOrderDTO) {
        OrderDTO orderDTO = openOrderConverter.convert(createOrderDTO);

        orderDTO.setSource(OrderSourceEnum.External);
        orderDTO.setSourceId(LoginClientHolder.getClientId());
        orderDTO.setType(OrderTypeEnum.TO_B);
        orderDTO.setOrderTime(DateUtil.getDateline());
        orderDTO.setPaymentStatus(OrderPaymentStatusEnum.NOT_PAY);
        orderDTO.setItemList(openOrderConverter.convertItemList(createOrderDTO.getItemList()));
        orderDTO.setPaymentList(Collections.emptyList());
        orderDTO.setTotalPrice(CurrencyUtil.sum(orderDTO.getItemList(), OrderItemDTO::getTotalPrice));
        orderDTO.setDiscountPrice(CurrencyUtil.sum(orderDTO.getItemList(), OrderItemDTO::getDiscountPrice));
        orderDTO.setTaxPrice(CurrencyUtil.sum(orderDTO.getItemList(), OrderItemDTO::getTaxPrice));
        orderDTO.setPayPrice(CurrencyUtil.sum(orderDTO.getItemList(), OrderItemDTO::getPayPrice));
        orderDTO.setDepositPrice(CurrencyUtil.sum(orderDTO.getPaymentList(), OrderPaymentDTO::getPrice));

        return orderManager.add(orderDTO);
    }

}

